package cn.tedu.knows.auth.service;

import cn.tedu.knows.commons.model.Permission;
import cn.tedu.knows.commons.model.Role;
import cn.tedu.knows.commons.model.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

// 将这个类保存到Spring容器
@Component
public class UserDetailsServiceImpl implements
                                    UserDetailsService {
    @Resource
    private RestTemplate restTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获得用户信息并判断是否存在
        String url=
          "http://sys-service/v1/auth/user?username={1}";
        User user=restTemplate.getForObject(
                            url,User.class,username);
        if(user==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 根据用户id查询所有权限和所有角色
        url="http://sys-service/v1/auth/permissions?id={1}";
        // 当我们Ribbon请求的服务器返回List类型时
        // 要使用List的泛型类型数组来接收返回值
        Permission[] permissions=restTemplate.getForObject(
                url,Permission[].class,user.getId());
        url="http://sys-service/v1/auth/roles?id={1}";
        Role[] roles=restTemplate.getForObject(
                url,Role[].class,user.getId());
        // 定义包含所有角色和权限的数组
        String[] auth=new String[permissions.length +
                                            roles.length];
        int i=0;
        for(Permission p: permissions){
            auth[i++]=p.getName();
        }
        for(Role r: roles){
            auth[i++]=r.getName();
        }
        // 构建UserDetails对象
        UserDetails u= org.springframework.security.core
                .userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(auth)
                .accountLocked(user.getLocked()==1)
                .disabled(user.getEnabled()==0)
                .build();
        // 最后千万别忘了返回u
        return u;
    }
}
